<!DOCTYPE HTML>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>增删改查</title>

    <link href="admin/plugins/bootstrap-3.3.0/css/bootstrap.min.css" rel="stylesheet"/>
    <link href="admin/plugins/material-design-iconic-font-2.2.0/css/material-design-iconic-font.min.css" rel="stylesheet"/>
    <link href="admin/plugins/bootstrap-table-1.11.0/bootstrap-table.min.css" rel="stylesheet"/>
    <link href="admin/plugins/waves-0.7.5/waves.min.css" rel="stylesheet"/>
    <link href="admin/plugins/jquery-confirm/jquery-confirm.min.css" rel="stylesheet"/>
    <link href="admin/plugins/font_73je1zmu39/iconfont.css" rel="stylesheet" />

    <link href="admin/css/common.css" rel="stylesheet"/>

    <style>
        /*将所有元素的默认间距清除，方便自己设置，并且可以消除ul和li的圆点*/
        * {
            margin:0px;
            padding:0px;
        }
        ul {
            background:#fff;
            box-shadow:0 0 10px rgba(0,0,0,0.2);
            /*x坐标，y坐标，模糊程度，颜色*/
            white-space:nowrap;
            /*避免文字换行*/
        }
        ul li {
            position:relative;
        }
        ul li a {
            text-decoration:none;
            color:#777;
            padding:10px 20px;
            display:block;
            background: bottom right no-repeat;
        }
        ul li a:only-child {
            background:none;
        }
        ul li:hover {
            background:#777;
        }
        ul li:hover > a {
            color:#fff;
        }
        ul li:hover > ul {
            display:block;
            /* 鼠标进入母选单後，显示子选单 */
        }
        nav > ul > li {
            display:inline-block;
            /* 使一级选单排成一列 */
        }
        ul ul {
            position:absolute;
            top:100%;
            list-style:none;
            background:#fff;
            box-shadow:0 3px 3px rgba(0,0,0,0.2);
            display:none;
        }
        ul ul ul {
            position:absolute;
            left:100%;
            top:0;
        }
    </style>
</head>
<body>
<div id="main">
    <div id="toolbar">
        <a class="waves-effect waves-button" href="javascript:;" onclick="createAction()"><i class="zmdi zmdi-plus"></i> 新增类别</a>
        <a class="waves-effect waves-button" href="javascript:;" onclick="updateAction()"><i class="zmdi zmdi-edit"></i> 编辑类别</a>
        <a class="waves-effect waves-button" href="javascript:;" onclick="deleteAction()"><i class="zmdi zmdi-close"></i> 删除类别</a>
    </div>
    <table id="table"></table>
</div>
<div id="template" class="jconfirm jconfirm-light" hidden>
    <div class="jconfirm-bg" style="transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1);">
    </div>
    <div class="jconfirm-scrollpane">
        <div class="jc-bs3-container container">
            <div class="jc-bs3-row row">
                <div class="jconfirm-box-container col-md-4 col-md-offset-4 col-sm-6 col-sm-offset-3 col-xs-10 col-xs-offset-1">
                    <div class="jconfirm-box jconfirm-hilight-shake jconfirm-dark jconfirm-type-animated" role="dialog" aria-labelledby="jconfirm-box93781" tabindex="-1" style="overflow: visible; margin-top: 50px; margin-bottom: 50px; transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1); transition-property: all, margin;">
                        <div class="jconfirm-closeIcon" style="display: none;">
                            ×
                        </div>
                        <div class="jconfirm-title-c">
                            <span class="jconfirm-icon-c"></span>
                            <span class="jconfirm-title">新增类别</span>
                        </div>
                        <div class="jconfirm-content-pane" style="overflow: visible;height: 100%; transition-duration: 0.3s; transition-timing-function: cubic-bezier(0.36, 0.55, 0.19, 1);">
                            <div class="jconfirm-content" id="jconfirm-box93781">
                                <form>
                                    <div class="form-group">
                                        <label for="category_parent" style="margin: 5px">上级类别</label>
                                        <input id="category_parent" name="category_parent" type="text" class="form-control" style="border: none; outline: none; pointer-events: none;tab-index:'-1'">
                                        <nav class="" >
                                            <ul>
                                                <li><a><span class="iconfont icon-xiala"></span></a>
                                                    <ul name="categoryList">
                                                        <li categoryId='0'><a onclick='selectCategory(this, 0)'>无</a><ul categoryId='0'></ul></li>
                                                    </ul>
                                                </li>
                                            </ul>
                                        </nav>
                                    </div>
                                    <div class="form-group">
                                        <label for="category_name" style="margin: 5px">类别名称</label>
                                        <input id="category_name" name="category_name" type="text" class="form-control">
                                    </div>
                                </form>
                            </div>
                        </div>
                        <div class="jconfirm-buttons">
                            <button type="button" name="confirm" class="btn waves-effect waves-button">确认</button>
                            <button type="button" onclick="$('#template').attr('hidden', true);" class="btn waves-effect waves-button">取消</button>
                        </div>
                        <div class="jconfirm-clear"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script src="admin/plugins/jquery.1.12.4.min.js"></script>
<script src="admin/plugins/bootstrap-3.3.0/js/bootstrap.min.js"></script>
<script src="admin/plugins/bootstrap-table-1.11.0/bootstrap-table.min.js"></script>
<script src="admin/plugins/bootstrap-table-1.11.0/locale/bootstrap-table-zh-CN.min.js"></script>
<script src="admin/plugins/waves-0.7.5/waves.min.js"></script>
<script src="admin/plugins/jquery-confirm/jquery-confirm.min.js"></script>

<script src="admin/js/common.js"></script>
<script>
    var $table = $('#table');
    $(function() {
        $(document).on('focus', 'input', function() {
            $(this).parent().find('label').addClass('active');
        }).on('blur', 'input', function() {
            if ($(this).val() == '') {
                $(this).parent().find('label').removeClass('active');
            }
        });
        // bootstrap table初始化
        // http://bootstrap-table.wenzhixin.net.cn/zh-cn/documentation/
        $table.bootstrapTable({
            url: "/api/category/v/getAllCategory",
            height: getHeight(),
            striped: true,
            search: true,
            dataType: "json",
            showRefresh: true,
            showToggle: true,
            showColumns: true,
            minimumCountColumns: 2,
            showPaginationSwitch: true,
            clickToSelect: true,
            detailView: true,
            detailFormatter: 'detailFormatter',
            pagination: true,
            paginationLoop: false,
            classes: 'table table-hover table-no-bordered',
            responseHandler: function(res) {
                console.log(res)
                return JSON.parse(res.data);
            },
            // sidePagination: 'server',
            //silentSort: false,
            smartDisplay: false,
            idField: 'id',
            sortName: 'id',
            sortOrder: 'desc',
            escape: true,
            searchOnEnterKey: true,
            maintainSelected: true,
            toolbar: '#toolbar',
            columns: [
                {field: 'state', checkbox: true},
                {field: 'categoryParent', title: '父类别', sortable: true, valign: 'center'},
                {field: 'categoryName', title: '类别', sortable: true, valign: 'center'},
                {field: 'remark', title: '备注', sortable: true, valign: 'center'},
                {field: 'action', title: '操作', valign: 'center', align: 'center', formatter: 'actionFormatter', events: 'actionEvents', clickToSelect: false}
            ],
            onLoadSuccess: (res) => {
                console.log(res);
            }
        }).on('all.bs.table', function (e, name, args) {
            $('[data-toggle="tooltip"]').tooltip();
            $('[data-toggle="popover"]').popover();
        });
    });
    function actionFormatter(value, row, index) {
        return [
            // '<a class="like" href="javascript:void(0)" data-toggle="tooltip" title="Like"><i class="glyphicon glyphicon-heart"></i></a>　',
            '<a class="edit ml10" href="javascript:void(0)" data-toggle="tooltip" title="Edit"><i class="glyphicon glyphicon-edit"></i></a>　'
            // '<a class="remove ml10" href="javascript:void(0)" data-toggle="tooltip" title="Remove"><i class="glyphicon glyphicon-remove"></i></a>'
        ].join('');
    }

    window.actionEvents = {
        'click .like': function (e, value, row, index) {
            alert('You click like icon, row: ' + JSON.stringify(row));
            console.log(value, row, index);
        },
        'click .edit': function (e, value, row, index) {
            alert('You click edit icon, row: ' + JSON.stringify(row));
            console.log(value, row, index);
        },
        'click .remove': function (e, value, row, index) {
            alert('You click remove icon, row: ' + JSON.stringify(row));
            console.log(value, row, index);
        }
    };
    function detailFormatter(index, row) {
        var html = [];
        $.each(row, function (key, value) {
            html.push('<p><b>' + key + ':</b> ' + value + '</p>');
        });
        return html.join('');
    }
    // 新增
    function createAction() {
        var categoryList = getCategory(0);
        drawCategory(categoryList);
        $("span.jconfirm-title").text("新增类别");
        $("#template").attr("hidden", null);
        $("input[name='category_parent']").val("").parentsUntil("form").last().find('label').removeClass('active');
        $("input[name='category_name']").val("").parentsUntil("form").last().find('label').removeClass('active');
        $("div.jconfirm-buttons button[name='confirm']").off("click").on("click", function () {
            addCategory();
        });
    }
    // 编辑
    function updateAction() {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length != 1) {
            $.confirm({
                title: false,
                content: '请选择一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            var categoryList = getCategory(0);
            drawCategory(categoryList);
            $("span.jconfirm-title").text("修改类别");
            $("#template").attr("hidden", null);
            $("input[name='category_parent']").val(rows[0].categoryParent==null ? "无" : rows[0].categoryParent).attr("categoryId", rows[0].categoryParentId).parentsUntil("form").last().find('label').addClass('active');
            $("input[name='category_name']").val(rows[0].categoryName).parentsUntil("form").last().find('label').addClass('active');
            $("div.jconfirm-buttons button[name='confirm']").off("click").on("click", function () {
                updateCategory();
            });
        }
    }
    // 删除
    function deleteAction() {
        var rows = $table.bootstrapTable('getSelections');
        if (rows.length == 0) {
            $.confirm({
                title: false,
                content: '请至少选择一条记录！',
                autoClose: 'cancel|3000',
                backgroundDismiss: true,
                buttons: {
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else if (rows.length == 1){
            $.confirm({
                type: 'red',
                animationSpeed: 300,
                title: false,
                content: '确认删除该类别吗？',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'waves-effect waves-button',
                        action: function () {
                            deleteCategory();
                        }
                    },
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        } else {
            $.confirm({
                type: 'red',
                animationSpeed: 300,
                title: false,
                content: '确认删除这些类别吗？',
                buttons: {
                    confirm: {
                        text: '确认',
                        btnClass: 'waves-effect waves-button',
                        action: function () {
                            console.log(rows);
                            var categories = new Array();
                            rows.forEach((item, index) => {
                                var category = new Object();
                                category.categoryName = item.categoryName;
                                category.categoryId = item.categoryId;
                                category.categoryParent = item.categoryParentId;
                                categories.push(category);
                            });
                            deleteCategories(categories);
                        }
                    },
                    cancel: {
                        text: '取消',
                        btnClass: 'waves-effect waves-button'
                    }
                }
            });
        }
    }
    //获取类别
    function getCategory(categoryId) {
        var formData = new FormData();
        formData.append("categoryId", categoryId);
        var result;
        $.ajax({
            type: "post",
            url: "/api/category/v/getCategoryByParent",
            dataType: "text",
            data: formData,
            async: false,
            processData: false,
            contentType: false,
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    result = JSON.parse(data.data);
                }else {
                    result = [];
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
        return result;
    }
    //渲染类别
    function drawCategory(categoryList) {
        if (categoryList.length>0) {
            if ($("ul[name='categoryList']").children().length<=1 ||
                (categoryList[0].categoryParent!==0 && $("ul[categoryId='" + categoryList[0].categoryParent + "']").children().length <= 0)) {
                categoryList.forEach((item, index) => {
                    if (item.categoryParent === 0) {
                        $("ul[name='categoryList']").append("<li categoryId='" + item.categoryId + "' flag=true onmouseover='console.log(123);getChildrenCategory(this)'><a onclick='selectCategory(this," + item.categoryId + ")'>" + item.categoryName + "</a><ul categoryId='" + item.categoryId + "'></ul></li>")
                    } else {
                        $("ul[categoryId='" + item.categoryParent + "']").append("<li categoryId='" + item.categoryId + "' flag=true onmouseover='console.log(123);getChildrenCategory(this)'><a onclick='selectCategory(this," + item.categoryId + ")'>" + item.categoryName + "</a><ul categoryId='" + item.categoryId + "'></ul></li>");
                    }
                });
            }
        }
    }
    //获得子类
    function getChildrenCategory(e) {
        if (e.getAttribute("flag") === "true") {
            e.setAttribute("flag", "false");
            var categoryList = getCategory(e.getAttribute("categoryId"));
            drawCategory(categoryList);
        }
    }
    //获得选择的类别
    function selectCategory(e, categoryId) {
        $("input[name='category_parent']").val($(e).text());
        $("input[name='category_parent']").attr("categoryId", categoryId);
        $(e).parentsUntil("form").last().find('label').addClass('active');
    }
    //类别上传
    function addCategory() {
        var categoryParent = $("input[name='category_parent']").attr("categoryId");
        var categoryName = $("input[name='category_name']").val();
        if (categoryName==="" || typeof(categoryName)===undefined || categoryParent==="" || typeof(categoryParent)===undefined) {
            alert("不能为空");
            return false;
        }
        $.ajax({
            type: "post",
            url: "/api/category/a/addCategory",
            dataType: "text",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify({
                "categoryParent" : categoryParent,
                "categoryName": categoryName
            }),
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    location.reload();
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
    }
    //类别修改
    function updateCategory() {
        var categoryId = $table.bootstrapTable('getSelections')[0].categoryId;
        var categoryName = $("input[name='category_name']").val();
        var categoryParent = $("input[name='category_parent']").attr("categoryId");
        if (categoryName==="" || typeof(categoryName)===undefined || categoryParent==="" || typeof(categoryParent)===undefined) {
            alert("不能为空");
            return false;
        }
        $.ajax({
            type: "post",
            url: "/api/category/a/modifyCategory",
            dataType: "text",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify({
                "categoryId" : categoryId,
                "categoryName": categoryName,
                "categoryParent": categoryParent
            }),
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    location.reload();
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
    }
    //删除类别
    function deleteCategory() {
        var categoryId = $table.bootstrapTable('getSelections')[0].categoryId;
        var categoryName = $table.bootstrapTable('getSelections')[0].categoryName;
        var categoryParent = $table.bootstrapTable('getSelections')[0].categoryParentId;
        $.ajax({
            type: "post",
            url: "/api/category/a/deleteCategory",
            dataType: "text",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify({
                "categoryId" : categoryId,
                "categoryName": categoryName,
                "categoryParent": categoryParent
            }),
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    location.reload();
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
    }
    //批量删除类别
    function deleteCategories(categories) {
        $.ajax({
            type: "post",
            url: "/api/category/a/deleteCategories",
            dataType: "text",
            contentType: "application/json;charset=UTF-8",
            data: JSON.stringify(categories),
            success: data => {
                data = eval('('+ data +')');
                if (data.success) {
                    location.reload();
                }else {
                    alert(data.msg);
                }
            },
            error: function (xhr, textStatus, errorThrown) {
                const msg = xhr.responseText;
                console.log(msg);
            }
        });
    }
</script>
</body>
</html>